package cs.android.model;

import static cs.java.lang.Lang.iterate;
import static cs.java.lang.Lang.json;
import static cs.java.lang.Lang.map;
import static cs.java.lang.Lang.no;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import cs.android.viewbase.ContextPresenter;
import cs.java.collections.MapItem;
import cs.java.json.JSONData;
import cs.java.json.JSONObject;

public class SettingsBase extends ContextPresenter {

	public static final String SHARED_PREFERENCES_KEY = "settings";

	protected SharedPreferences getPreferences() {
		return getContext().getSharedPreferences(SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE);
	}

	protected void save(String... keysvalues) {
		Editor editor = getPreferences().edit();
		for (MapItem<String, String> keyvalue : iterate(map(keysvalues)))
			editor.putString(keyvalue.key(), keyvalue.value());
		editor.commit();
	}

	public <T extends JSONData> T load(T data, String key) {
		String loadString = loadString(key);
		if (no(loadString)) return null;
		JSONObject json = json(loadString).asObject();
		if (no(json)) return null;
		data.load(json);
		return data;
	}

	public boolean loadBoolean(String key) {
		return loadBoolean(key, false);
	}

	public boolean loadBoolean(String key, boolean defaultValue) {
		return getPreferences().getBoolean(key, defaultValue);
	}

	public String loadString(String key) {
		return getPreferences().getString(key, null);
	}

	public void save(String key, Boolean value) {
		Editor editor = getPreferences().edit();
		editor.putBoolean(key, value);
		editor.commit();
	}

	public void save(String key, JSONData data) {
		save(key, data.save().toJSON());
	}

	public void save(String key, String value) {
		Editor editor = getPreferences().edit();
		editor.putString(key, value);
		editor.commit();
	}
}
